<script setup>
import { Search, Refresh, Top } from "@element-plus/icons-vue";
import { ref, onMounted, computed, provide } from 'vue';
import categoryData from './category.json';
import { useRouter } from 'vue-router';
import request, { SERVER_BASE_URL } from '@/utils/request';
import { ElInfiniteScroll } from 'element-plus';

const router = useRouter();
// 添加搜索功能逻辑
const searchQuery = ref('');
const handleSearch = () => {
  console.log('Search query:', searchQuery.value);
  // 这里可以添加实际的搜索逻辑
};

// 处理分类点击事件
const handleCategoryClick = (category) => {
  router.push({ 
    path: '/category', 
    query: { tag: category.Tag } 
  });
};

// 初始化分类数据
const allCategories = ref([]);
const maxDisplayCategories = 27; // 限制为15个分类，3行5列布局，不需要滚动条

// 随机打乱数组顺序
const shuffleArray = (array) => {
  const newArray = [...array];
  for (let i = newArray.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
  }
  return newArray;
};

// 计算要显示的分类
const category = computed(() => {
  return allCategories.value.slice(0, maxDisplayCategories);
});

// 加载更多商品 - 触发CommodityView组件的loadMore方法
const loadMore = () => {
  // console.log('IndexView触发无限滚动');
  // 尝试通过window触发一个全局自定义事件
  window.dispatchEvent(new CustomEvent('index-scroll-bottom'));
};

// 在组件挂载时随机排序分类
onMounted(() => {
  // 随机打乱顺序
  allCategories.value = shuffleArray(categoryData);
});

// 刷新分类
const refreshCategories = () => {
  allCategories.value = shuffleArray(categoryData);
};

// 处理图片URL
const getImgUrl = (url) => {
  if (!url) return '';

  // 确保有服务器地址前缀
  const serverBaseUrl = SERVER_BASE_URL;
  let fullUrl = url;

  if (url.startsWith('/uploads/')) {
    fullUrl = serverBaseUrl + url;
  }

  return fullUrl;
};
</script>

<template>
  <el-container v-infinite-scroll="loadMore" style="width: 100%;padding-top: 30px;position: relative;" infinite-scroll-distance="10" infinite-scroll-delay="200">
    <el-header style="height: auto;">
      <el-card style="width: 90%; margin: 0 auto;">
        <!-- 搜索框和按钮 -->
        <div style="display: flex; align-items: center; justify-content: space-between;">
          <!-- 标题 -->
          <div class="logo-text">
            <h1>Campus</h1>
            <p>校园网上超市</p>
          </div>

          <div style="display: flex; align-items: center; flex: 1;">
            <el-input
              type="primary"
              v-model="searchQuery"
              placeholder="请输入搜索内容(商品名称、商品分类、商品标签)"
              @keyup.enter="handleSearch"
              style="flex: 1; margin-right: 10px;"
            >
            </el-input>
            <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          </div>
        </div>
      </el-card>

      <div style="display: flex; justify-content: space-between; margin: 20px auto; width: 90%;">
        <el-card class="category-card" style="width: 28%; max-height: 450px; overflow-y: auto;">
          <template #header>
            <div class="category-header">
              <el-text style="font-size: 18px;" tag="b">
                <span style="color: black;">商品分类</span>
              </el-text>
              <div class="category-actions">
                <el-button size="small" type="primary" :icon="Refresh" circle @click="refreshCategories" title="刷新分类" plain></el-button>
              </div>
            </div>
          </template>

          <!-- 分类列表 - 网格布局 -->
          <div class="category-grid">
            <div v-for="(item, index) in category" :key="index" class="category-item">
              <el-tag size="default" :type="index % 5 === 0 ? 'primary' : index % 5 === 1 ? 'success' : index % 5 === 2 ? 'warning' : index % 5 === 3 ? 'danger' : 'info'" 
                     effect="light" class="category-tag" @click="handleCategoryClick(item)">
                {{ item.name }}
              </el-tag>
            </div>
          </div>
        </el-card>

        <el-carousel trigger="click" height="450px" style="width: 70%;box-shadow: 0 5px 12px rgba(0, 0, 0, 0.3);">
          <el-carousel-item v-for="item in 4" :key="item">
            <img 
              :src="`/src/assets/carousel/${item}.png`"
              style="width: 100%; height: 100%; object-fit: cover"
            />
          </el-carousel-item>
        </el-carousel>
      </div>
    </el-header>

    <el-main style="width: 95%; height: 100%; padding: 0; margin: auto; overflow-y: auto;">
      <div class="title-section">
        <div class="title-wrapper">
          <h2>猜你喜欢</h2>
          <div class="title-decoration"></div>
        </div>
      </div>
      
      <div class="main-content">
        <router-view></router-view>
      </div>

    </el-main>
  </el-container>
  
  <!-- 返回顶部按钮 -->
  <el-backtop :right="40" :bottom="40" :visibility-height="200" target=".el-main">
    <div class="back-top-box">
      <el-icon><Top /></el-icon>
    </div>
  </el-backtop>
</template>

<style scoped>
.logo-text {
  display: flex;
  flex-direction: column;
  min-width: 180px;
}

.logo-text h1 {
  margin: 0;
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  line-height: 1.2;
}

.logo-text p {
  margin: 0;
  font-size: 16px;
  color: #666;
  line-height: 1.2;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 20px;
}

.category-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.category-card {
  transition: all 0.3s;
}

.category-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  justify-content: center;
}

.category-item {
  display: flex;
  justify-content: center;
  max-width: 100%;
  height: 30px;
}

.category-tag {
  width: 100%;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 0 6px;
  max-width: 100%;
  box-sizing: border-box;
  height: 30px;
  line-height: 30px;
  border-radius: 4px;
}

.category-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.title-section {
  margin-bottom: 12px;
  position: relative;
}

.title-wrapper {
  position: relative;
  display: inline-block;
}

.title-section h2 {
  font-size: 18px;
  color: #409EFF;
  margin: 2px;
  font-weight: 600;
  position: relative;
  display: inline-block;
}

.title-decoration {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(90deg, #409EFF 0%, #67C23A 100%);
  border-radius: 4px;
}

.main-content {
  min-height: calc(100vh - 650px); /* 确保内容区有足够的高度 */
}

/* 推荐商品列表样式 */
.commodity-list {
  width: 100%;
  min-height: 200px;
}

.commodity-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.commodity-card {
  border-radius: 10px;
  transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  cursor: pointer;
  overflow: hidden;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
  background-color: #fff;
  border: 1px solid #EBEEF5;
  padding: 5px;
}

.commodity-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 25px rgba(0, 0, 0, 0.2);
}

.commodity-card:hover .card-overlay {
  opacity: 1;
}

.commodity-image {
  height: 200px;
  overflow: hidden;
  border-radius: 10px 10px 0 0;
  position: relative;
}

.card-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.view-details {
  color: white;
  font-size: 14px;
  font-weight: 500;
  padding: 6px 14px;
  border-radius: 20px;
  background-color: rgba(64, 158, 255, 0.8);
}

.commodity-info {
  padding: 10px;
  font-size: 14px;
}

.commodity-name {
  font-size: 15px;
  margin: 0 0 6px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #303133;
  font-weight: 500;
}

.commodity-price {
  font-size: 18px;
  color: #ff6700;
  font-weight: bold;
  margin-bottom: 5px;
}

.commodity-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.commodity-sales, .commodity-stock {
  font-size: 12px;
  color: #909399;
}

.loading-container {
  text-align: center;
  padding: 20px 0;
}

.loading-text {
  color: #409EFF;
  font-size: 14px;
  margin-top: 8px;
}

.no-more-text {
  color: #909399;
  font-size: 14px;
  margin-top: 8px;
  position: relative;
  display: inline-block;
  padding: 0 20px;
}

.commodity-fade-enter-active,
.commodity-fade-leave-active {
  transition: all 0.5s ease;
}

.commodity-fade-enter-from {
  opacity: 0;
  transform: translateY(30px);
}

.commodity-fade-leave-to {
  opacity: 0;
}

.back-top-box {
  width: 40px;
  height: 40px;
  background-color: #409EFF;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  border-radius: 50%;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
  transition: all 0.3s;
}

.back-top-box:hover {
  background-color: #66b1ff;
  transform: scale(1.1);
}
</style>